package cn.bdqn.config.shiro;

import cn.bdqn.pojo.Right;
import cn.bdqn.pojo.Role;
import cn.bdqn.pojo.User;
import cn.bdqn.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MyShiroRealm extends AuthorizingRealm {//数据源
    @Resource
    UserService userService;
    @Resource
    StringRedisTemplate stringRedisTemplate;



    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

            //获取登录用户
            User user=(User)principalCollection.getPrimaryPrincipal();
            SimpleAuthorizationInfo info=
                    new SimpleAuthorizationInfo();
//            //静态授权
//            info.addRole(user.getRole().getRoleName());
//            info.addStringPermission("用户列表");
//            if("管理员".equals(user.getRole().getRoleName())){
//                info.addStringPermission("用户添加");
//                info.addStringPermission("用户编辑");
//                info.addStringPermission("用户删除");
//            }
        //动态授权
        Role role=user.getRole();
        if(role!=null){
            info.addRole(role.getRoleName());
            List<Right> rights = role.getRights();
            if(rights!=null&&rights.size()>0){
                for (Right right : rights) {
                    info.addStringPermission(right.getRightCode());
                }
            }
        }
            return info;
        }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        ValueOperations<String, String> vo = stringRedisTemplate.opsForValue();
        vo.increment("shiro_login_count"+token.getUsername(),1);
        if (Integer.parseInt(vo.get("shiro_login_count"+token.getUsername()))>5){
            vo.set("shiro_is_lock"+token.getUsername(),"lock", 1,TimeUnit.HOURS);
            stringRedisTemplate.delete("shiro_login_count"+token.getUsername());
        }

        if (("lock").equals(vo.get("shiro_is_lock" + token.getUsername()))){
            throw new DisabledAccountException("账号不可用");
        }


        //构造认证信息（也就是根据传过来的用户名查询数据库）
        User user=userService.getUserByUsrName(token.getUsername());


        if(user==null){//没查询到数据；说明数据库没有该账号
            throw new UnknownAccountException("账号不存在");
        }
        if(user.getUsrFlag()==0){//账号被锁定
            throw new LockedAccountException("账号被锁定");
        }


        //构造用户信息（用户名和密码组成）
        return new SimpleAuthenticationInfo(user,
                user.getUsrPassword(), ByteSource.Util.bytes("czkt"),getName());
    }
}
